package com.zzld.modules.autoinn.action;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.abel533.entity.Example;
import com.github.pagehelper.PageInfo;
import com.zzld.core.utils.Base64Coder;
import com.zzld.core.utils.CookieUtils;
import com.zzld.core.utils.GeoUtil;
import com.zzld.modules.autoinn.entity.Area;
import com.zzld.modules.autoinn.entity.Collect;
import com.zzld.modules.autoinn.entity.Customer;
import com.zzld.modules.autoinn.entity.Expense;
import com.zzld.modules.autoinn.entity.Store;
import com.zzld.modules.autoinn.service.IAreaService;
import com.zzld.modules.autoinn.service.ICollectService;
import com.zzld.modules.autoinn.service.ICustomerService;
import com.zzld.modules.autoinn.service.IExpenseService;
import com.zzld.modules.autoinn.service.IProductPingService;
import com.zzld.modules.autoinn.service.IStoreService;
import com.zzld.modules.common.dto.AreaSelect;
import com.zzld.modules.common.dto.CommonJSON;
import com.zzld.modules.common.dto.NavCat;
import com.zzld.modules.common.dto.NavTab;
import com.zzld.modules.common.dto.SortSelect;

@Controller
@RequestMapping("/weixin/f/autoinn/xc/store")
public class WXStoreController {

	@Autowired
	private IStoreService storeService;

	@Autowired
	private IAreaService areaService;

	@Autowired
	private IProductPingService productPingService;

	@Autowired
	private ICollectService collectService;

	@Autowired
	private ICustomerService customerService;

	@Autowired
	private IExpenseService expenseService;

	private String listurl = "/wx/autoinn/xc_store_list";
	private String delurl = "/wx/autoinn/xc_store_detail";

	@RequestMapping(value = "test", method = RequestMethod.GET)
	public String wxtest(Model model, HttpServletRequest request) {
		// 获取父级区域参数和子集区域参数
		String area_f = request.getParameter("area_f");
		String area_sub = request.getParameter("area_sub");
		// 获取排序参数
		String sort = request.getParameter("sort");
		NavCat navCat = getNavCat(area_f, area_sub, sort);
		model.addAttribute("navCat", navCat);
		return listurl;
	}

	/**
	 * 列表页面get请求方法
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String wxstorelist(Model model, HttpServletRequest request) {
		// 获取父级区域参数和子集区域参数
		String area_f = request.getParameter("area_f");
		String area_sub = request.getParameter("area_sub");
		// 获取排序参数
		String sort = request.getParameter("sort");
		NavCat navCat = getNavCat(area_f, area_sub, sort);
		model.addAttribute("navCat", navCat);

		String openid = CookieUtils.getCookie(request, "autoinn_session");
		String wxaccount = CookieUtils.getCookie(request, "wx_session");
		Customer customer = null;
		try {
			openid = Base64Coder.decode(openid);
			wxaccount = Base64Coder.decode(wxaccount);
			customer = customerService.findCustomer(wxaccount, openid);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		Example example = new Example(Collect.class);
		example.createCriteria().andEqualTo("openid", openid)
				.andEqualTo("customerId", customer.getCustomerId());
		try {
			if (collectService.selectByExample(example).size() > 0) {
				model.addAttribute("shou", 1);
			} else {
				model.addAttribute("shou", 0);
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return listurl;
	}

	@RequestMapping("/pagelist")
	@ResponseBody
	public CommonJSON wxxcstore(Model model, HttpServletRequest request) {
		CommonJSON result = new CommonJSON();
		Map<String, Object> map = new HashMap<String, Object>();
		// 区域ID
		String area_f = request.getParameter("area_f");
		String area_sub = request.getParameter("area_sub");
		String sou = request.getParameter("sou");

		if (area_f != null && area_f.equals("null")) {
			area_f = null;
		}

		if (area_sub != null && area_sub.equals("null")) {
			area_sub = null;
		}

		map.put("area_f", area_f);
		map.put("area_sub", area_sub);
		if(sou!=null && !sou.equals("null")){
			map.put("name", sou);
		}else{
			map.put("name", null);
		}

		// lng经度,lat纬度
		String lng = request.getParameter("lng") == null ? "0" : request
				.getParameter("lng").toString();

		String lat = request.getParameter("lat") == null ? "0" : request
				.getParameter("lat").toString();
		request.getSession().setAttribute("lng", request.getParameter("lng"));
		request.getSession().setAttribute("lat", request.getParameter("lat"));
		Integer pageNum = Integer
				.parseInt(request.getParameter("pageNum") == null ? "1"
						: request.getParameter("pageNum"));

		if(lng ==null|| lng.equals("null")){
			lng="0";
		}
		if(lat == null || lat.equals("null")){
			lat="0";
		}
		double longitude = Double.parseDouble(lng);
		double latitude = Double.parseDouble(lat);

		// 获取排序
		String sort = request.getParameter("sort") == null ? "jlzj" : request
				.getParameter("sort");
		if (sort.equals("null")) {
			sort = "jlzj";
		}
		map.put("lat", latitude==0.0?null:latitude);
		map.put("lng", longitude==0.0?null:longitude);

		// 排序为距离最近
		if (sort.equals("jlzj") || sort.equals("default")) {
			try {
				PageInfo<Store> storeList = storeService.selectOrderDistance(
						map, pageNum, 10);
				result.setSuccess(true);
				// 总条数
				result.setTotal(storeList.getTotal());
				result.setRows(storeList.getList());
			} catch (Exception e) {
				e.printStackTrace();
				result.setSuccess(false);
			}
		} else if (sort.equals("sold")) { // 评分
			try {
				PageInfo<Store> storeList = storeService.selectOrderfen(map,
						pageNum, 10);
				result.setSuccess(true);
				// 总条数
				result.setTotal(storeList.getTotal());
				result.setRows(storeList.getList());
			} catch (Exception e) {
				e.printStackTrace();
				result.setSuccess(false);
			}
		} else if (sort.equals("jgpx")) {// 价格排序
			try {
				PageInfo<Store> storeList = storeService.selectOrderprice(map,
						pageNum, 10);
				result.setSuccess(true);
				// 总条数
				result.setTotal(storeList.getTotal());
				result.setRows(storeList.getList());
			} catch (Exception e) {
				e.printStackTrace();
				result.setSuccess(false);
			}
		}
		return result;

	}

	@RequestMapping(value = "deltail", method = RequestMethod.GET)
	public String wxxdel(Model model, HttpServletRequest request) {

		String id = request.getSession().getAttribute("qid").toString();
		// lng经度,lat纬度
		String lng = request.getSession().getAttribute("lng").toString() == null ? "0"
				: request.getSession().getAttribute("lng").toString();

		String lat = request.getSession().getAttribute("lat").toString() == null ? "0"
				: request.getSession().getAttribute("lat").toString();
          
		/* String id = "402880ed4c36277f014c36277fee0000";
		 String lng = "106.23268600000000000";
		 String lat = "38.48245300000000000";*/
		String openid = CookieUtils.getCookie(request, "autoinn_session");
		String wxaccount = CookieUtils.getCookie(request, "wx_session");

		try {
			openid = Base64Coder.decode(openid);
			wxaccount = Base64Coder.decode(wxaccount);

		} catch (Exception e1) {
			e1.printStackTrace();
		}

		model.addAttribute("wxacont", wxaccount);
		if (!id.equals("") && id != null) {

			Map<String, Object> msp = storeService.selectbykey(id);
			if (!lat.equals("0") && !lng.equals("0")) {
				double j = GeoUtil.getDistance(Double.valueOf(lat),
						Double.valueOf(lng),
						Double.valueOf(msp.get("lat").toString()),
						Double.valueOf(msp.get("lng").toString()));
				BigDecimal bd = new BigDecimal(j);
				bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
				int qo = fen(id);
				msp.put("comment_val", qo);
				msp.put("stoid", id);
				msp.put("juli", "距离" + bd.toString() + "km");
			} else {
				msp.put("juli", "暂无信息");
			}

			// 浏览量
			// 创建一个session对象
			
		    String d = "";
		    
		
		    try {
			    
		         if(request.getSession().getAttribute("sy"+openid)!=null){
		        	 d=request.getSession().getAttribute("sy"+openid).toString();
		         }else{
		        	d="0"; 
		         }
		    	
				 if(d.equals("0")){

			    	 int i = Integer.valueOf(d);
			    	 int looknum = Integer.valueOf(msp.get("looknum").toString());
					 i++;
				     looknum=looknum+i;
				   
				     Store store = new Store();
				     store.setId(msp.get("stoid").toString());
				     store.setLooknum(looknum);
				     if(storeService.updateByPrimaryKeySelective(store)>0){
				    	 request.getSession().setAttribute("sy"+openid, "1");
				     }
				 }
			       
			} catch (Exception e2) {
				// TODO 自动生成的 catch 块
				e2.printStackTrace();
			}
			// 浏览量 结束

			model.addAllAttributes(msp);
			model.addAttribute("p", storeService.selectbyprice(id));

			model.addAttribute("ding", expenseService.selectbystorecount(id));

			Example e = new Example(Collect.class);
			e.createCriteria().andEqualTo("id", id)
					.andEqualTo("openid", openid);

			try {
				List<Collect> c = collectService.selectByExample(e);
				if (collectService.selectByExample(e).size() > 0) {
					model.addAttribute("oi", 1);
				}
			} catch (Exception e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
			model.addAttribute("storeid", id);
			boolean isId = msp.containsKey("id");
			if (isId) {
				model.addAttribute("proid", msp.get("id").toString());
			}
		}

		return delurl;
	}

	public int fen(String storeid) {
		// 参与评论人数
		int counts = productPingService.selectbycount(storeid);
		// 评论总分数
		int fe = productPingService.selectbysum(storeid);

		if (counts == 0 || fe == 0) {
			return 0;
		}
		double q = fe / counts;

		BigDecimal bd = new BigDecimal(q);
		bd = bd.setScale(0, BigDecimal.ROUND_HALF_UP);

		return Integer.parseInt(bd.toString());
	}

	@RequestMapping(value = "deltail", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> wxxdels(Model model, ModelMap momap,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!request.getParameter("id").equals(null)
				&& !request.getParameter("id").equals("")) {
			request.getSession()
					.setAttribute("qid", request.getParameter("id"));

			map.put("url", "/weixin/f/autoinn/xc/store/deltail");
		}
		return map;
	}

	/**
	 * 
	 * @Title: deltail
	 * @Description: TODO 根据ID获得详情
	 * @param:@param model
	 * @param:@param momap
	 * @param:@param request
	 * @param:@return
	 * @return: Map<String,Object>
	 * @throws 
	 */
	@RequestMapping(value = "deltail/{id}")
	public String deltail(Model model, ModelMap map,
			HttpServletRequest request, @PathVariable("id") String id) {
		String openid = CookieUtils.getCookie(request, "autoinn_session");
		String wxaccount = CookieUtils.getCookie(request, "wx_session");
		try {
			openid = Base64Coder.decode(openid);
			wxaccount = Base64Coder.decode(wxaccount);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		model.addAttribute("wxacont", wxaccount);
		if (!id.equals("") && id != null) {
			Map<String, Object> msp = storeService.selectbykey(id);
			int qo = fen(id);
			msp.put("comment_val", qo);
			msp.put("stoid", id);

			model.addAllAttributes(msp);
			model.addAttribute("p", storeService.selectbyprice(id));

			Example e = new Example(Collect.class);
			e.createCriteria().andEqualTo("id", id)
					.andEqualTo("openid", openid);
			try {
				List<Collect> collectList = collectService.selectByExample(e);
				if (collectList != null && collectList.size() > 0) {
					model.addAttribute("oi", 1);
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			model.addAttribute("storeid", id);
			boolean isId = msp.containsKey("id");
			if (isId) {
				model.addAttribute("proid", msp.get("id").toString());
			}
		}
		return delurl;
	}

	/**
	 * 获取筛选排序拼装
	 * 
	 * @param area_f
	 * @param area_sub
	 * @param sort
	 * @return
	 */
	private NavCat getNavCat(String area_f, String area_sub, String sort) {
		NavCat navCat = new NavCat(); // 返回拼装结果对象
		List<NavTab> navtabList = new ArrayList<NavTab>();
		List<AreaSelect> areaList = new ArrayList<AreaSelect>();
		List<SortSelect> sortList = new ArrayList<SortSelect>();

		String nav_tab_arae = "全部区域";
		String nav_tab_sort = "距离最近";
		String nav_tab_cqmd = "常去门店";

		if (StringUtils.isBlank(sort)) {
			sort = "default";
		}

		List<Area> area_p_list = null;
		// 查询区域父级并加载
		try {
			Example fexample = new Example(Area.class);
			fexample.createCriteria().andEqualTo("level", 2);
			area_p_list = areaService.selectByExample(fexample);

			// 拼接默认区域参数
			AreaSelect fas = new AreaSelect();
			fas.setText("全部区域");
			fas.setDatamain("area_emptyMenu");
			fas.setHref("/weixin/f/autoinn/xc/store?sort=" + sort);
			if (StringUtils.isBlank(area_f)) {
				fas.setSelect("select");
			}
			areaList.add(fas);

			if (area_p_list != null) {
				for (Area area : area_p_list) {
					List<Area> area_sub_list = new ArrayList<Area>();
					List<AreaSelect> subaslist = new ArrayList<AreaSelect>();

					// 拼接父级区域数据
					AreaSelect areaselect = new AreaSelect();
					areaselect.setDatamain("area_" + area.getId());
					areaselect.setText(area.getAreaname());
					areaselect.setHref("/weixin/f/autoinn/xc/store?area_f="
							+ area.getId() + "&sort=" + sort);
					if (StringUtils.isNotBlank(area_f)
							&& area_f.equals(area.getId())) {
						nav_tab_arae = area.getAreaname();
						areaselect.setSelect("select");
					}

					// 拼接子级区域数据
					Example subexample = new Example(Area.class);
					subexample.createCriteria().andEqualTo("pid", area.getId());
					area_sub_list = areaService.selectByExample(subexample);
					if (area_sub_list != null) {
						for (Area subarea : area_sub_list) {
							AreaSelect subareaselect = new AreaSelect();
							subareaselect
									.setHref("/weixin/f/autoinn/xc/store?area_f="
											+ area.getId()
											+ "&area_sub="
											+ subarea.getId() + "&sort=" + sort);
							subareaselect.setText(subarea.getAreaname());
							if (StringUtils.isNotBlank(area_sub)
									&& area_sub.equals(subarea.getId())) {
								nav_tab_arae = subarea.getAreaname();
								subareaselect.setSelect("select");
							}
							subaslist.add(subareaselect);
						}
						areaselect.setSubList(subaslist);
					} else {
						areaselect.setHref("/weixin/f/autoinn/xc/store?area_f="
								+ area.getId() + "&sort=" + sort);
						areaselect.setDatamain("area_emptyMenu");
					}

					areaList.add(areaselect);
				}
			}
			String sort_url = "/weixin/f/autoinn/xc/store?";
			if (StringUtils.isNotBlank(area_f) && StringUtils.isBlank(area_sub)) {
				sort_url += "area_f=" + area_f + "&";
			} else if (StringUtils.isBlank(area_f)
					&& StringUtils.isNotBlank(area_sub)) {
				sort_url += "area_sub=" + area_sub + "&";
			} else if (StringUtils.isNotBlank(area_f)
					&& StringUtils.isNotBlank(area_sub)) {
				sort_url += "area_f=" + area_f + "&area_sub=" + area_sub + "&";
			}
			// sort

			SortSelect mrSortSelect = new SortSelect();
			mrSortSelect.setText("距离最近");
			mrSortSelect.setHref(sort_url + "sort=jlzj");
			if (sort.equals("jlzj")) {
				nav_tab_sort = "距离最近";
				mrSortSelect.setSelect("select");
			}
			sortList.add(mrSortSelect);

			SortSelect sortSelect1 = new SortSelect();
			sortSelect1.setText("评分最高");
			sortSelect1.setHref(sort_url + "sort=sold");
			if (sort.equals("sold")) {
				nav_tab_sort = "评分最高";
				sortSelect1.setSelect("select");
			}
			sortList.add(sortSelect1);

			SortSelect sortSelect3 = new SortSelect();
			sortSelect3.setText("价格排序");
			sortSelect3.setHref(sort_url + "sort=jgpx");
			if (sort.equals("jgpx")) {
				nav_tab_sort = "价格排序";
				sortSelect3.setSelect("jgpx");
			}
			sortList.add(sortSelect3);

			// 菜单显示项目
			NavTab nav_area_tab = new NavTab();
			nav_area_tab.setDataType("area");
			nav_area_tab.setText(nav_tab_arae);
			navtabList.add(nav_area_tab);

			NavTab nav_sort_tab = new NavTab();
			nav_sort_tab.setDataType("sort");
			nav_sort_tab.setText(nav_tab_sort);
			navtabList.add(nav_sort_tab);

			NavTab nav_cqmd_tab = new NavTab();
			nav_cqmd_tab.setDataType("cqmd");
			nav_cqmd_tab.setText(nav_tab_cqmd);
			navtabList.add(nav_cqmd_tab);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		navCat.setAreaList(areaList);
		navCat.setNavtabList(navtabList);
		navCat.setSortList(sortList);
		return navCat;
	}

}
